<?php

namespace App\Http\Middleware;

use App\Kuafu\User\Model\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class InternalApiAuth
{
    protected function errorMessage(): \Illuminate\Http\JsonResponse
    {
        return response()->json([
            'code' => 401,
            'msg'  => '尚未登录',
            'data' => null,
        ]);
    }

    public function handle(Request $request, \Closure $next)
    {
        $userId = $request->header('userId', 0);
        if (!empty($userId)) {
            $userInfo = User::query()->find($userId);
            auth('api')->login($userInfo);
        }
        $key   = $request->header('internal-key', '');
        $token = $request->header('internal-token', '');
        if (config('app.env') == 'dev') {
            return $next($request);
        }
        if ('' === $key || '' === $token) {
            return $this->errorMessage();
        }

        $tokens = config('InternalAPI.tokens');
        if (($tokens[$key] ?? null) === $token) {
            return $next($request);
        }

        return $this->errorMessage();
    }
}
